const { spawn } = require('child_process')
const path = require('path')
const fs = require('fs')
const pathResolve = (dir) => path.resolve(__dirname, dir)

const argv = require('minimist')(process.argv.slice(2))
let defaultConfig = {
  port: 7033,
  mp: 'weixin',
  outputDir: undefined,
}
let finalConfig = {}
let devConfig = readDevConfig()
finalConfig = Object.assign(finalConfig, defaultConfig, devConfig, argv)

createServer(finalConfig)

function readDevConfig() {
  let configPath = pathResolve('./../../dev-config.js')
  return require(configPath)
}

function runMpDev(config) {
  let { mp, outputDir, name, customPath } = config
  let cmd = `cross-env NODE_ENV=development UNI_PLATFORM=mp-${mp} CROSS_BUILD_TYPE=local vue-cli-service uni-build --watch`
  if (outputDir) {
    cmd += ` --subpackage=${name}`
    if (customPath) {
      process.env.UNI_OUTPUT_DIR = outputDir
    } else {
      process.env.UNI_OUTPUT_DIR = path.resolve(outputDir, 'tempSubpages', name)
    }
    process.env.CLEAN_STATIC = '1'
    process.env.OUTPUT_LOCAL = '1'
  }
  const child = spawn(cmd, [], { shell: true })

  child.stdout.on('data', (data) => {
    console.log(`${data}`)
  })
  child.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`)
  })

  child.on('close', (code) => {
    console.log(`child process exited with code ${code}`)
  })
}

function getIp() {
  const os = require('os')
  const interfaces = os.networkInterfaces()
  for (let key in interfaces) {
    let interface = interfaces[key]
    for (let i = 0; i < interface.length; i++) {
      let item = interface[i]
      if (item.family === 'IPv4' && !item.internal) {
        return item.address
      }
    }
  }
}

function createServer(config) {
  let { port } = config
  const http = require('http')
  const obj = {
    '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.html': 'text/html;charset=utf8',
    '.js': 'application/javascript;charset=utf8',
    '.css': 'text/css;charset=utf8',
  }
  const server = http.createServer((req, res) => {
    let url = req.url === '/' ? '/index.html' : req.url
    url = url.replace(/\?.*/, '')
    const filePath = pathResolve('../../src' + url)
    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.statusCode = 404
        res.end('not found')
      } else {
        const extName = path.extname(filePath)
        if (obj[extName]) {
          res.setHeader('content-type', obj[extName])
        }
        res.end(data)
      }
    })
  })

  server.on('error', (e) => {
    if (e.code === 'EADDRINUSE') {
      console.log(`端口${port}被占用，尝试新的端口`)
      server.close()
      port++
      createServer({ ...config, port })
    }
  })

  server.listen(port, () => {
    if (finalConfig.out) {
      process.env.LOCAL_SERVER = `http://127.0.0.1:${port}`
    } else {
      process.env.LOCAL_SERVER = `http://${getIp()}:${port}`
    }
    console.log('服务器启动成功，地址：', process.env.LOCAL_SERVER)
    runMpDev(config)
  })
}
